package com.example.springbootdemo.web;

import com.google.gson.Gson;
import lombok.Data;
import org.springframework.web.bind.annotation.RestController;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.*;

@RestController
@ServerEndpoint("/talk/{id}")
public class TalkAction {

    private static Map<String, Session> sessionMap = new Hashtable<>();

    @OnOpen
    public void onOpen(@PathParam("id") String id, Session session) throws IOException {
        session.getUserProperties().put("id", id);
        sessionMap.put(id, session);
        System.out.println("sessionMap = " + sessionMap);
        sendMsg(id, id + " 上线了!");
    }

    @OnClose
    public void onClose(Session session) throws IOException {
        String id = (String) session.getUserProperties().get("id");
        sessionMap.remove(id);
        System.out.println("sessionMap = " + sessionMap);
        sendMsg(id, id + " 下线了!");
    }

    @OnMessage
    public void onMessage(String msg, Session session) throws IOException {
        String id = (String) session.getUserProperties().get("id");
        sendMsg(id, msg);
    }

    // 群发
    public void sendMsg(String id, String msg) throws IOException {
        System.out.println("msg = " + msg);
        Message m = new Message();
        m.text = msg;
        m.id = id;
        m.users = sessionMap.keySet();
        Gson gson = new Gson();
        final String j = gson.toJson(m);
        for (Session session : sessionMap.values()) {
            final RemoteEndpoint.Basic basicRemote = session.getBasicRemote();
            basicRemote.sendText(j);
        }
    }

    @Data
    class Message {
        String text;
        String id;
        Collection<String> users;
    }

}

